#!/bin/bash
# 创建数据目录
cd /opt/software/openGauss
mkdir data

# 下载编译好的三方库并解压(这里下载的是Centos7.6_x86_64的版本，在7.6和7.9都能用)
# wget https://opengauss.obs.cn-south-1.myhuaweicloud.com/5.0.0/binarylibs/openGauss-third_party_binarylibs_Centos7.6_x86_64.tar.gz
# tar -xvf openGauss-third_party_binarylibs_Centos7.6_x86_64.tar.gz
cp   /home/openGauss-third_party-5.0.0.zip  /opt/software/openGauss
cp   /home/openGauss-server-5.0.0.zip  /opt/software/openGauss

unzip openGauss-third_party-5.0.0.zip
# 克隆数据库源码仓
# git clone https://gitee.com/opengauss/openGauss-server -b 5.0.0
unzip openGauss-server-5.0.0.zip

# 配置环境变量(这里最核心的一点就是把gcc的默认路径改了，操作系统默认的版本太低)
echo "export CODE_BASE=/opt/software/openGauss/openGauss-server-5.0.0     # Path of the openGauss-server file " >> ~/.bashrc
echo "export BINARYLIBS=/opt/software/openGauss/openGauss-third_party-5.0.0    # Path of the binarylibs file " >> ~/.bashrc
echo "export GAUSSHOME=\$CODE_BASE/dest/ " >> ~/.bashrc
echo "export GCC_PATH=\$BINARYLIBS/buildtools/gcc7.3/ " >> ~/.bashrc
echo "export CC=\$GCC_PATH/gcc/bin/gcc " >> ~/.bashrc
echo "export CXX=\$GCC_PATH/gcc/bin/g++ " >> ~/.bashrc
echo "export LD_LIBRARY_PATH=\$GAUSSHOME/lib:\$GCC_PATH/gcc/lib64:\$GCC_PATH/isl/lib:\$GCC_PATH/mpc/lib/:\$GCC_PATH/mpfr/lib/:\$GCC_PATH/gmp/lib/:\$LD_LIBRARY_PATH " >> ~/.bashrc
echo "export PATH=\$GAUSSHOME/bin:\$GCC_PATH/gcc/bin:\$PATH " >> ~/.bashrc
echo "export PGDATA=/opt/software/openGauss/data" >> ~/.bashrc
echo "export PGPORT=5432" >> ~/.bashrc
echo "export PGDATABASE=postgres" >> ~/.bashrc

# 加载环境变量
source ~/.bashrc

# 进入源码目录
cd $CODE_BASE

# 编译server (这里就是openGauss提供的一键式编译脚本)
sh build.sh -m release -3rd $BINARYLIBS

# 文件夹改名 (原文档说会生成dest目录，但实际上是生成到了mppdb_temp_install，所以改个名)
mv mppdb_temp_install dest 

# 克隆插件仓，并复制到server源码目录内(必须单独编译，因为如果先放到server源码内，server都会编译不成功)
git clone https://gitee.com/opengauss/Plugin -b 5.0.0
cp Plugin/contrib/*  $CODE_BASE/contrib/ -r

# 编译dolphin插件
cd contrib/dolphin
make install

# 复制插件到编译好的server目录
cp *.so $GAUSSHOME/lib/postgresql/ 
cp *.control $GAUSSHOME/share/postgresql/extension/ 
cp *.sql $GAUSSHOME/share/postgresql/extension/ 

# 初始化数据库
gs_initdb --nodename=primary --pwpasswd=Sinvie@123

# 配置一些数据库参数
echo "port=$PGPORT" >> $PGDATA/postgresql.conf
echo "listen_addresses = '0.0.0.0'" >> $PGDATA/postgresql.conf
echo "password_encryption_type = 0" >> $PGDATA/postgresql.conf
echo "log_directory = 'pg_log'" >> $PGDATA/postgresql.conf
echo "remote_read_mode=non_authentication" >> $PGDATA/postgresql.conf
echo "host all all 0.0.0.0/0 md5" >> $PGDATA/pg_hba.conf

# 启动数据库
gs_ctl start 

# 连接数据库并创建一个B库
gsql -c "create database CMEP dbcompatibility='B'";

# 开启一些mysql特性
gsql -c "alter database CMEP set enable_set_variable_b_format = on;";
gsql -c "alter database CMEP set dolphin.lower_case_table_names = 0;";
gsql -c "alter database CMEP set dolphin.B_COMPATIBILITY_MODE = on;";
gsql -c "alter system set  enable_dolphin_proto= on;";
gsql -c "alter system set  dolphin_server_port=3306;";

gs_ctl restart